import React, { Component } from 'react';
import classnames from 'classnames';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Row, Col, Modal, message, Spin } from 'antd';
import { WeaAlertPage, WeaInputSearch, WeaLocaleProvider, WeaPopoverHrm } from 'ecCom';
import { WeaTableNew } from 'comsMobx';
import NewGroupVoting from './New';
import VoteDetails from './VoteDetails';
import List from './list/LeftList';

const getLabel = WeaLocaleProvider.getLabel;
const { confirm } = Modal;
let WeaTable = WeaTableNew.WeaTable;

@inject('listStore', 'newStore')
@observer
export default class GroupList extends Component {
  static defaultProps = {
    prefixCls: 'group-voting-list',
  };

  constructor(props) {
    super(props);
    this.viewVote = this.viewVote.bind(this);
  }

  componentDidMount() {
    const { listStore: { getGroupVoteList, setStoreState }, location: { query } } = this.props;
    const queryId = window.location.href.match(
      new RegExp('[?&]id=([^&]*)(&?)', 'i'),
    );
    if (window.em) {
      em.ready(() => {
        const that = this;
        em.getTargetInfo({
          success(res) {
            let params = { groupid: res.targetId, isgroup: res.targetType, title: res.targetName || '' };
            setStoreState(params);
            getGroupVoteList(params, '', () => {
              const id = queryId && queryId[1];
              if (id) {
                  that.viewVote(id);
              }
            });
          },
          fail(res) {
            message.error(res.errMsg, '方法请求失败');
          },
        });
      });
    } else {
      getGroupVoteList('', '', () => {
        const id = queryId && queryId[1];
        if (id) {
            this.viewVote(id);
        }
      });
    }
  }

  renderNoData = () => (
    <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@efrqhf`}
      icon={<i className="icon-coms-blank" />}
      className={'group-voting-noSearch'}
      top={'30%'}
    >
      <div style={{ color: '#999', paddingTop: 10 }}>{getLabel('83320', '没有可显示的数据')}</div>
    </WeaAlertPage>
  )

  renderItem = (record) => {
    const { prefixCls } = this.props;
    return (
      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@wtby1e`}
        className={`${prefixCls}-item`}
        onClick={() => this.viewVote(record.id)}
      >
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@tcov9p`} span={23} className={`${prefixCls}-item-info`}>
          <div className={`${prefixCls}-item-info-theme`}>
            {/* <span className={`wea-f14 name`}>{record.votetheme}</span> */}
            <span className={'wea-f14 name'} dangerouslySetInnerHTML={{ __html: record.votetheme }} />
            {record.votestatusspan === '0' ? (
              <span className="group-voting-state-ing">{getLabel('1960', '进行中')}</span>
            ) : (
              <span className="group-voting-state-end">{getLabel('22348', '已结束')}</span>
            )}
          </div>
          <div className={`${prefixCls}-item-info-creater`}>
            <span>{record.createridspan}</span>
            <span>{`${record.createdatespan} ${record.createtimespan}`}</span>
          </div>
        </Col>
        {
          record.canDelspan === '1' && (
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@s0f8n1`} span={1} className={`${prefixCls}-item-ops`}>
              <i
                className="icon-coms-Delete"
                onClick={e => this.deleteVote(e, record)}
              />
            </Col>
          )
        }
      </Row>
    );
  };

  getColumns = (columns) => {
    let newColumns = '';
    const {
      prefixCls,
      listStore: { groupListStore },
    } = this.props;
    const selectedRowKeys = toJS(groupListStore.selectedRowKeys);
    newColumns = columns.map((column) => {
      let newColumn = column;
      if (newColumn.dataIndex === 'votetheme') {
        newColumn.render = (text, record, index) => this.renderItem(record);
        newColumn.title = (
          <div className={`${prefixCls}-list-container-list-title`}>
            <span>{getLabel('556', '全选')}</span>
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@v0kc2m@${newColumn.dataIndex}`}
              type="primary"
              disabled={selectedRowKeys.length === 0}
              onClick={() => this.handleShare(selectedRowKeys)}
            >{`${getLabel('126091', '分享')}(${selectedRowKeys.length})`}</Button>
          </div>
        );
      } else {
        newColumn.render = (text, record, index) => {
          let valueSpan =
            record[`${newColumn.dataIndex}span`] !== undefined
              ? record[`${newColumn.dataIndex}span`]
              : record[newColumn.dataIndex];
          return <div dangerouslySetInnerHTML={{ __html: valueSpan }} />;
        };
      }
      return newColumn;
    });
    return newColumns;
  };

  /* 新建群投票 */
  newGroupVoting = () => {
    const { listStore: { setStoreState }, newStore } = this.props;
    const { initiateVote } = newStore;
    setStoreState({ newVisible: true }, initiateVote);
  };

  /* 查看投票 */
  viewVote = (id) => {
    const { listStore } = this.props;
    const { setStoreState, viewGroupVote, groupListStore } = listStore;
    setStoreState({ selectedKeys: [], isShowDetail: true, voteId: id, checkedRowKeys: id });
    if (this.votedetail && this.votedetail.wrappedInstance) this.votedetail.wrappedInstance.setState({ canVote: true });
    viewGroupVote({ votingid: id });
    groupListStore.tableUpdate({ showCheck: false });
    groupListStore.setRowCheckKey([id]);
  };

  /* 删除投票 */
  deleteVote = (e, record) => {
    e.stopPropagation();
    const { listStore } = this.props;
    const { groupchatvotedel, voteId } = listStore;
    const that = this;
    window.setDialogFullWindow = false;
    confirm({
      title: getLabel('506504', '确定要删除该投票吗?'),
      onOk() {
        groupchatvotedel({ votingid: record.id });
        if (voteId === record.id) {
          that.onCancelDetail();
        }
      },
    });
  };

  onCancelDetail = () => {
    const { listStore } = this.props;
    const { setStoreState, groupListStore } = listStore;
    setStoreState({ isShowDetail: false, dataInfo: {} });
    groupListStore.tableUpdate({ showCheck: true });
  };

  /* 投票分享 */
  handleShare = (selectedRowKeys) => {
    const { listStore } = this.props;
    const { groupchatvoteshare, groupid, isgroup } = listStore;
    window.setDialogFullWindow = false;
    confirm({
      title: getLabel('516169', '确定要分享所选投票吗？'),
      onOk() {
        groupchatvoteshare({
          votingid: selectedRowKeys.join(),
          isgroup,
          groupid,
        }, (result) => {
          if (result.voteInfo && result.voteInfo.length > 0) {
            result.voteInfo.forEach((item) => {
              const { votingid, votetheme, enddate, endtime, themeimagesrc } = item;
              if (window.em) {
                em.sendMsg({
                  targetId: '', // 消息会话ID
                  msgType: 10, // 消息类型：1-文本 2-链接 10-E6分享消息
                  msgInfo: {
                    content: votetheme, // 分享标题（必填）
                    desc: `${getLabel('18111', '截止时间：')} ${enddate} ${endtime}`, // 分享描述（非必填）
                    canforward: 0, // 消息是否允许转发 1：是（默认） 0：否
                    callbackurl: '', // 消息转发回调地址（非必填）
                    sharetypename: getLabel('514291', '群投票'), // 消息类型显示标题，没有则按sharetype显示
                    sharetypeicon: '', // 消息类型显示图标
                    sharetypebgcolor: '', // 消息类型背景颜色，没有则按sharetype显示
                    showimage: themeimagesrc, // 消息显示图片地址，没有则不显示图片
                    linkurl: `/spa/groupVote/static4mobile/index.html#/voting/${votingid}`, // 消息链接地址（必填）
                    linkurl_pc: `/spa/smallApp/static/index.html#/main/groupVoting/groupVotingList?id=${votingid}`, // PC端消息链接地址，如果没有则取linkurl值
                    sharetype: 'voting', // 分享数据类型,值有"doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
                    shareid: votingid, // 分享的数据ID（必填）
                    opentype: 1, // 移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
                    opentype_pc: 1, // PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                  },
                  success: (res) => {
                    // console.log('success',res)
                  },
                  fail: (res) => {
                    // console.log('fail',res)
                  },
                });
              }
            });
          }
        });
      },
    });
  };

  render() {
    const { prefixCls, listStore } = this.props;
    const { groupListStore, isShowDetail, getListData,
      listLoading,
      getGroupVoteList,
      setStoreState,
      isSearch,
      isgroup,
      listReloadLoading,
      checkedRowKeys,
    } = listStore;
    const datas = toJS(groupListStore).datas;
    const paginationProps = isShowDetail
      ? {
          total: toJS(groupListStore).count || 0,
          pageSize: toJS(groupListStore).pageSize || 10,
          current: toJS(groupListStore).current || 1,
          size: 'small',
          showTotal: () => '',
          showQuickJumper: false,
          showSizeChanger: false,
          onChange: (curt) => {
            getListData('', curt);
          },
        }
      : undefined;
    const listCls = classnames({
      [`${prefixCls}-list`]: true,
      showDetail: isShowDetail,
    });
    const headerCls = classnames({
      [`${prefixCls}-list-header`]: true,
      isgroup,
    });
    if (listLoading && !isSearch) {
      return (
        <div className={prefixCls}>
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@urvfk6`} />
        </div>
      );
    } else if (datas && datas.length === 0 && !isSearch && !listLoading && isgroup) {
      return (
        <div className={prefixCls}>
          <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@stk3zj`}
            icon={<i className="icon-portal-reportform" />}
            top={isgroup ? '23%' : '30%'}
          >
            <div style={{ color: '#999' }}>{getLabel('506508', '暂无投票，快去发布投票吧！')}</div>
            {isgroup && (
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kf4z2s`}
                className="group-voting-publish btnprimary"
                type="primary"
                onClick={this.newGroupVoting}
              >
                {getLabel('516170', '发布新投票')}
              </Button>
            )}
          </WeaAlertPage>
          <NewGroupVoting ecId={`${this && this.props && this.props.ecId || ''}_NewGroupVoting@rk28uk`} />
        </div>
      );
    } else if (datas && datas.length === 0 && !isSearch && !listLoading && !isgroup) {
      return this.renderNoData();
    }
    return (
      <div className={prefixCls}>
        <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@5m8chz`} inDialog={true} />
        <div className={listCls}>
          <div className={headerCls}>
            <div className={`${prefixCls}-list-header-search`}>
              <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@rzptmw`}
                placeholder={getLabel('516171', '搜索投票关键词')}
                onSearch={(v) => {
                  getGroupVoteList({ groupvotename: v });
                  setStoreState({ isSearch: true });
                }}
              />
            </div>
            {isgroup ? (
              <div className={`${prefixCls}-list-header-publish`}>
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j8w1wc`}
                  className={'btnprimary'}
                  type="primary"
                  onClick={this.newGroupVoting}
                >
                  {getLabel('513883', '发起新投票')}
                </Button>
              </div>
            ) : null}
          </div>
          <div className={`${prefixCls}-list-container`}>
            {datas.length === 0 && isSearch ? (
              this.renderNoData()
            ) : !isShowDetail ? (
              <div className={`${prefixCls}-list-container-list`}>
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@ktzl1u`}
                  ref="voteList"
                  // rowKey='id'
                  comsWeaTableStore={groupListStore}
                  needScroll
                  loading={listReloadLoading}
                  getColumns={this.getColumns}
                  showHeader={!isShowDetail}
                  paginationProps={paginationProps}
                  needRowClick
                />
              </div>
            ) : (
              <List ecId={`${this && this.props && this.props.ecId || ''}_List@gijqjt`}
                datas={datas}
                deleteVote={this.deleteVote}
                viewVote={this.viewVote}
                checkedRowKeys={checkedRowKeys}
                paginationProps={paginationProps}
              />
            )}
          </div>
        </div>
        <VoteDetails ecId={`${this && this.props && this.props.ecId || ''}_VoteDetails@2c7uw5`} ref={ref => this.votedetail = ref} />
        <NewGroupVoting ecId={`${this && this.props && this.props.ecId || ''}_NewGroupVoting@3l2xku`} />
      </div>
    );
  }
}
